
import 'package:flutter/material.dart';
import 'package:orginone/components/KeepAliveWidget/KeepAliveWidget.dart';
import 'package:orginone/components/EmptyWidget/EmptyActivity.dart';
import 'package:orginone/dart/core/thing/fileinfo.dart';
import 'package:orginone/dart/core/thing/standard/form.dart' as core;
import 'package:orginone/dart/core/chat/activity.dart';
import 'package:orginone/dart/core/thing/standard/application.dart';
import 'package:orginone/main.dart';
import 'package:orginone/pages/portal/assets_management/view.dart';
import 'package:orginone/pages/portal/morepage/share_page.dart';
import 'package:orginone/pages/portal/workBench/view.dart';
import 'package:orginone/routers/pages.dart';
import '../../components/CommandWidget/index.dart';
import '../../components/TabContainerWidget/TabContainerWidget.dart';
import '../../components/TabContainerWidget/types.dart';
import '../../routers/app_route.dart';
import 'cohort/CohortActivityWidget.dart';
import 'data_view/data_view_page.dart';

/// 门户页面
class PortalPage extends StatefulWidget {

  const PortalPage({super.key});

  @override
  State<StatefulWidget> createState() => _PortalPageState();
}

class _PortalPageState extends State<PortalPage> {
  TabContainerModel? relationModel;

  var data;
  List<TabItemsModel> tabItems = [];
  List<IFileInfo>? portalTopdata2;
  GroupActivity? cohortActivity;

  @override
  Widget build(BuildContext context) {
    return CommandWidget<AppRoute>(
        flag: 'switchSpace',
        builder: (context, args) {
          refreshData(true);
          return FutureBuilder(
            future: expensiveOperation(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                refreshData(false);
                return TabContainerWidget(relationModel!);
              }
              return TabContainerWidget(relationModel!);
              // return const Center(
              //   child: CircularProgressIndicator(),
              // );
            },
          );
        });
  }

  // 耗时操作
  Future<String> expensiveOperation() async {
    // Future.delayed(new Duration(seconds: 0),() async {
    // });
    cohortActivity = GroupActivity(
      relationCtrl.user!,
          () {
        return relationCtrl.data.home!.selectSpace.activitys;
      },
      true,
    );
    if (cohortActivity!.activitys.isEmpty ||
        cohortActivity!.activitys.length <= 1) {
      await cohortActivity!.load();
    }
    data = relationCtrl.data.home!.selectSpace!.cacheObj.getValue("homeConfig");
    portalTopdata2 = (await relationCtrl.loadCommonsTops(relationCtrl.data.home!.selectSpace));
    // .where((element) => element.typeName == '应用' && element.typeName == '视图' || element.typeName == '商城')
    // .toList();
    return '完成';
  }

  void load() {
    relationModel = TabContainerModel(
      title: "门户",
      activeTabTitle: getActiveTabTitle(),
      tabItems: tabItems,
    );
  }

  Future<void> refreshData(bool isFirstshow) async {
    tabItems.clear();
    tabItems.add(TabItemsModel(title: "工作台", content: buildWorkBench()));
    tabItems.add(TabItemsModel(title: "动态", content: buildDynamic()));
    if (!isFirstshow) {
      if (null != portalTopdata2 && portalTopdata2!.isNotEmpty) {
        portalTopdata2!.forEach((value) async {
          if (null != value) {
            if (data.toString().contains(value.id)) {
              // 添加模板
              if (value.typeName == "应用") {
                tabItems.add(TabItemsModel(
                    title: value.name, content: buildAppManagement((value as Application))));
              } else if (value.typeName == "视图") {
                tabItems.add(TabItemsModel(
                    title: value.name, content: buildDataView(value as core.Form)));
              } else {
                tabItems.add(TabItemsModel(
                    title: value.name, content: buildMorePage()));
              }
            }
          }
        });
      }
    }
    load();
  }

  /// 获得激活页签
  getActiveTabTitle() {
    return RoutePages.getRouteDefaultActiveTab()?.firstOrNull;
  }

  /// 构建工作台
  Widget buildWorkBench() {
    return const WorkBenchPage();
  }

  /// 构建数据试图
  Widget buildDataView(core.Form form) {
    return DataViewPage(form: form);
  }

  ///构建应用模版视图
  Widget buildAppManagement(Application appdata) {
    return AppManagementPage(xappdata: appdata);
  }

  ///构建个人资产管理
  // Widget buildPersonalAssetManagement() {
  //   return PersonalAssetsManagementPage();
  // }

  //构建共享页面
  Widget buildMorePage() {
    return const SharePage();
  }

  /// 构建群动态
  Widget buildDynamic() {
    // GroupActivity? cohortActivity = GroupActivity(
    //   relationCtrl.user!,
    //       () {
    //     return relationCtrl.data.home!.selectSpace.activitys;
    //   },
    //   true,
    // );
    return null != cohortActivity
        ? KeepAliveWidget(
            child: CohortActivityWidget(
            "activity",
            "群动态",
            cohortActivity!,
          ))
        : const EmptyActivity();
  }

  /// 构建好友圈
  Widget buildFriends() {
    GroupActivity? friendsActivity =
        relationCtrl.provider.chatProvider?.activityProvider.friendsActivity;
    return null != friendsActivity && null != relationCtrl.user
        ? KeepAliveWidget(
            child: CohortActivityWidget(
            "circle",
            "好友圈",
            friendsActivity,
          ))
        : const EmptyActivity();
    // } else {
    //   return Container(
    //     child: const Center(child: Text("--暂无好友圈内容--")),
    //   );
    // }
  }
}
